import { getToken, removeToken, setToken } from '@/utils/auth'
import { loginAPI, getUserProfileAPI, getUserPhotoAPI } from '@/api'

const getDefaultState = () => {
  return {
    token: getToken(), // 用户token
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}// 用户信息对象
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 设置token
  SET_TOKEN(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 删除token
  REMOVE_TOKEN(state) {
    state.token = ''
    removeToken()
  },
  // 设置用户信息
  SET_USERINFO(state, value) {
    state.userInfo = value
    localStorage.setItem('userInfo', JSON.stringify(value))
  },
  // 删除用户信息
  REMOVE_USER(state) {
    state.userInfo = {}
    localStorage.removeItem('userInfo')
  }
}

const actions = {
  // 登录逻辑
  async loginActions({ commit }, value) {
    const res = await loginAPI(value)
    // console.log({ commit })
    // console.log(value)
    commit('SET_TOKEN', res.data)
    // console.log(res)
    return res
  },
  // 获取用户信息
  async getUserInfoActions({ commit }, value) {
    const res = await getUserProfileAPI() // 获取用户基本资料对象
    // console.log(res)
    const user = await getUserPhotoAPI(res.data.userId)
    // console.log(user)
    commit('SET_USERINFO', { ...res.data, ...user.data }) // 保存到vuex的userInfo对象里
  },
  // 退出登录
  async logOutActions({ commit }) {
    commit('REMOVE_TOKEN')
    commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
